package com.jin.utils;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;

import java.io.IOException;

/**
 * Created on 2025/5/1.
 * @author Zhongyuan Jin
 */
public class StrictIntegerDeserializer extends JsonDeserializer<Integer> {

    @Override
    public Integer deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        JsonToken token = p.getCurrentToken();

        switch (token) {
            case VALUE_STRING:
                String text = p.getText().trim();
                if (text.isEmpty()) {
                    return null; // 允许空字符串转为 null
                }
                if ("undefined".equalsIgnoreCase(text)) {
                    throw ctxt.weirdStringException(text, Integer.class, "非法整数值");
                }
                try {
                    return Integer.parseInt(text);
                } catch (NumberFormatException e) {
                    throw ctxt.weirdStringException(text, Integer.class, "无法转换为整数");
                }

            case VALUE_NUMBER_INT:
                return p.getValueAsInt(); // 直接读取整数

            default:
                throw ctxt.weirdStringException(p.getText(), Integer.class, "不支持的类型");
        }
    }
}